#include "base.h"
#include <rtthread.h>

static struct rt_event event;

#define EVENT_KEY_PRESSED       (1 << 0)
#define EVENT_UART_PRESSED      (1 << 1)

void key_entry (void * param) {
    while (1) {
        if (key_pressed()) {           
            // noitify
            rt_event_send(&event, EVENT_KEY_PRESSED);
        }
        rt_thread_mdelay(500);
    }
}

void uart_entry (void * param) {
    while (1) {
        if (uart_available()) {
            uart_read();
            
            // notify
            rt_event_send(&event, EVENT_UART_PRESSED);
        }
        rt_thread_mdelay(100);
    }
}

void recv_entry (void * param) {
    rt_uint32_t recv;
    while (1) {
        rt_event_recv(&event, 
            EVENT_KEY_PRESSED | EVENT_UART_PRESSED,
            RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR ,
            RT_WAITING_FOREVER,
            &recv);
        
        if (recv & EVENT_KEY_PRESSED) {
            rt_kprintf("key pressed\n");
        }
        
        if (recv & EVENT_UART_PRESSED) {
            rt_kprintf("uart data\n");
        }
    }
}

int main(void) {
    hardware_init();
    
    rt_event_init(&event, "event", RT_IPC_FLAG_FIFO);
    
    rt_thread_t t1 = rt_thread_create("key", key_entry, RT_NULL, 1024, 10, 10);
    rt_thread_startup(t1);
    rt_thread_t t2 = rt_thread_create("uart", uart_entry, RT_NULL, 1024, 10, 10);
    rt_thread_startup(t2);
    rt_thread_t t3 = rt_thread_create("recv", recv_entry, RT_NULL, 1024, 10, 10);
    rt_thread_startup(t3);
    return 0;
}
